package com.jd.threed.信号量;


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * 信号量
 * 用来限制并发访问的资源
 *
 */
public class SemaphoreDemo {

    static Semaphore semaphore = new Semaphore(3);

    public static void main(String[] args) {

        ExecutorService executorService = Executors.newFixedThreadPool(50);

        for (int i=0;i<1000;i++) {
            executorService.submit(new Task());
        }
    }



    static class Task implements Runnable {

        @Override
        public void run() {

            try {
                semaphore.acquire();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"拿到了入场券");

            try {
                // 模拟慢应用
                Thread.sleep(3000);
                semaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"用掉了入场券");

        }
    }
}
